package com.whacos.common.shiro;

import com.whacos.common.config.ApplicationContextRegister;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.modules.system.entity.SysUser;
import com.whacos.modules.system.service.SysMenuService;
import com.whacos.modules.system.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.Set;

/**
 * @author xiongdun
 * @description ShiroUtils
 * @since 2018/11/17 17:11
 */
public class UserRealm extends AuthorizingRealm {

    private SessionDAO sessionDAO;

    @Autowired
    public void getSessionDAO(SessionDAO sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    /**
     * 授权
     *
     * @param arg0
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        SysMenuService menuService = ApplicationContextRegister.getBean(SysMenuService.class);
        Set<String> perms = menuService.listPermissionByUserId(ShiroUtils.getUserId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }

    /**
     * 验证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());

        // 处理Session， 实现一个用户只能在一台机器上登录
        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager.getSessionManager();
        // 获取当前已登录的用户session列表
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        for (Session session : sessions) {
            //清除该用户以前登录时保存的session
            SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session
                    .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (ObjectUtils.isNotEmpty(principalCollection)) {
                SysUser sysUser = (SysUser) principalCollection.getPrimaryPrincipal();
                String loginName = sysUser.getUsername();
                if (username.equals(loginName)) {
                    session.setTimeout(0L);
                    sessionManager.getSessionDAO().delete(session);
                }
            }
        }

        SysUserService sysUserService = ApplicationContextRegister.getBean(SysUserService.class);
        // 查询用户信息
        SysUser sysUser = sysUserService.get(username);

        // 账号不存在
        if (sysUser == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        // 密码错误
        if (!password.equals(sysUser.getPassword())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }

        // 账号锁定
        if (sysUser.getStatus() == 0) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        return new SimpleAuthenticationInfo(sysUser, password, getName());
    }

}
